<template>
  <div class="system-user-dialog-container">
    <el-dialog v-model="state.dialog.isShowDialog" :title="state.dialog.title" width="800px">
      <el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="rules" label-width="80px" size="default">
        <el-row :gutter="35">
          <el-col :span="12" class="mb20">
            <el-form-item label="会员" prop="memberId">
              <el-select v-model="state.ruleForm.memberId" clearable
                         placeholder="请选择会员"
                         size="default">
                <el-option
                    v-for="item in state.memberList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="mb20">
            <el-form-item label="优惠券" prop="templateId">
              <el-select v-model="state.ruleForm.templateId" clearable
                         placeholder="请选择优惠券"
                         size="default">
                <el-option
                    v-for="item in state.couponList"
                    :key="item.id"
                    :label="item.couponName"
                    :value="item.id"
                >
                   <span style="float: left">
                    {{ item.couponName }}
                  </span>
                  <span style="float: right; color: #8492a6; font-size: 13px; margin-left: 5px;">
                    {{ item.purpose }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12" class="mb20">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                  v-model="state.ruleForm.startTime"
                  placeholder="券开始时间"
                  style="width: 100%"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="mb20">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                  v-model="state.ruleForm.endTime"
                  placeholder="券结束时间"
                  style="width: 100%"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12" class="mb20">
            <el-form-item label="发放数量" prop="number">
              <el-input-number v-model="state.ruleForm.number" :min="1" controls-position="right"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="onCancel">取 消</el-button>
					<el-button size="default" type="primary" @click="onSubmit(userDialogFormRef)">
						{{ state.dialog.submitTxt }}
					</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="systemUserDialog" setup>
import {nextTick, onMounted, reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage} from 'element-plus';
import {couponTemplateApi} from "/@/api/market/coupon/template";
import {memberInfoApi} from "/@/api/member/info";
import {couponRecordApi} from "/@/api/market/coupon/record";
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    templateId: '',
    memberId: '',
    startTime: '',
    endTime: '',
    number: 1, // 发送数量
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  couponList: [],
  memberList: [],
});
const rules = reactive<FormRules>({
  templateId: [{required: true, message: '不能为空', trigger: 'blur'}],
  memberId: [{required: true, message: '不能为空', trigger: 'blur'}],
  startTime: [{required: true, message: '不能为空', trigger: 'blur'}],
  endTime: [{required: true, message: '不能为空', trigger: 'blur'}],
});
// 打开弹窗
const openDialog = (type: string) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  if (type === 'add') {
    state.dialog.title = '发券模版';
    state.dialog.submitTxt = '发券';
  }
  nextTick(() => {
    if (type === 'add') {
      // 清空表单，此项需加表单验证才能使用
      userDialogFormRef.value.resetFields();
    }
  });
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (state.dialog.type === 'add') {
        couponRecordApi()
            .addRecord(state.ruleForm)
            .then((res) => {
              if (res && res.code === 200) {
                ElMessage.success(res.msg || '新增成功');
                closeDialog();
                emit('refresh');
              }
            });
      }
    }
  });
};

// 页面加载时
onMounted(() => {
// 优惠券数据
  couponTemplateApi()
      .findAll()
      .then(res => {
        state.couponList = res.data;
      })

  // 会员数据
  memberInfoApi()
      .findAll()
      .then(res => {
        state.memberList = res.data;
      })

});

// 暴露变量
defineExpose({
  openDialog,
});
</script>
